import { defineStore } from 'pinia';
import { notificationsApi } from '@/api/notifications';

export const useNotificationsStore = defineStore('notifications', {
  state: () => ({
    notifications: [],
    emails: [],
    unreadCount: 0,
    totalCount: 0,
    loading: false,
    messageTypes: {},
    statistics: {
      total: 0,
      unread: 0,
      read: 0,
      byType: {}
    },
    // 新增分页相关状态
    pagination: {
      currentPage: 1,
      pageSize: 10,
      totalPages: 1,
      totalMessages: 0
    },
    // 新增刷新相关状态
    lastRefreshTime: null
  }),

  getters: {
    // 获取未读消息
    unreadNotifications: (state) => {
      return state.notifications.filter(n => !n.isRead);
    },
    
    // 获取已读消息
    readNotifications: (state) => {
      return state.notifications.filter(n => n.isRead);
    },
    
    // 获取未读邮件
    unreadEmails: (state) => {
      return state.emails.filter(e => !e.isRead);
    },
    
    // 获取已读邮件
    readEmails: (state) => {
      return state.emails.filter(e => e.isRead);
    },
    
    // 按类型分组消息
    notificationsByType: (state) => {
      const grouped = {};
      state.notifications.forEach(notification => {
        if (!grouped[notification.messageType]) {
          grouped[notification.messageType] = [];
        }
        grouped[notification.messageType].push(notification);
      });
      return grouped;
    },
    
    // 获取消息类型统计
    typeStatistics: (state) => {
      const stats = {};
      state.notifications.forEach(notification => {
        if (!stats[notification.messageType]) {
          stats[notification.messageType] = { total: 0, unread: 0 };
        }
        stats[notification.messageType].total++;
        if (!notification.isRead) {
          stats[notification.messageType].unread++;
        }
      });
      return stats;
    }
  },

  actions: {
    // 设置通知
    setNotifications(notifications) {
      this.notifications = notifications;
    },
    
    // 设置邮件
    setEmails(emails) {
      this.emails = emails;
    },
    
    // 设置未读数量
    setUnreadCount(count) {
      this.unreadCount = count;
    },
    
    // 设置总数量
    setTotalCount(count) {
      this.totalCount = count;
    },
    
    // 设置加载状态
    setLoading(loading) {
      this.loading = loading;
    },
    
    // 设置消息类型
    setMessageTypes(types) {
      this.messageTypes = types;
    },
    
    // 设置统计信息
    setStatistics(statistics) {
      this.statistics = statistics;
    },

    // 设置分页信息
    setPagination(pagination) {
      this.pagination = { ...this.pagination, ...pagination };
    },

    // 设置刷新时间
    setLastRefreshTime(time) {
      this.lastRefreshTime = time;
    },

    // 标记消息为已读
    async markAsRead(notificationId) {
      try {
        await notificationsApi.markAsRead(notificationId);
        // 更新本地状态
        const notification = this.notifications.find(n => n.notificationId === notificationId);
        if (notification) {
          notification.isRead = true;
        }
        // 重新加载未读数量
        await this.loadUnreadCount();
        return true;
      } catch (error) {
        console.error('标记已读失败:', error);
        return false;
      }
    },
    
    // 全部标记为已读
    async markAllAsRead() {
      try {
        await notificationsApi.markAllAsRead();
        // 更新本地状态
        this.notifications.forEach(notification => {
          notification.isRead = true;
        });
        this.setUnreadCount(0);
        return true;
      } catch (error) {
        console.error('全部标记已读失败:', error);
        return false;
      }
    },
    
    // 删除消息
    async deleteNotification(notificationId) {
      try {
        await notificationsApi.deleteNotification(notificationId);
        // 更新本地状态
        this.notifications = this.notifications.filter(n => n.notificationId !== notificationId);
        // 重新加载未读数量
        await this.loadUnreadCount();
        return true;
      } catch (error) {
        console.error('删除消息失败:', error);
        return false;
      }
    },
    
    // 删除所有消息
    async deleteAllNotifications() {
      try {
        await notificationsApi.deleteAllNotifications();
        // 更新本地状态
        this.setNotifications([]);
        this.setUnreadCount(0);
        return true;
      } catch (error) {
        console.error('删除所有消息失败:', error);
        return false;
      }
    },
    
    // 添加新消息（用于实时通知）
    addNotification(notification) {
      this.notifications.unshift(notification);
      if (!notification.isRead) {
        this.unreadCount++;
      }
    },
    
    // 更新消息
    updateNotification(updatedNotification) {
      const index = this.notifications.findIndex(n => n.notificationId === updatedNotification.notificationId);
      if (index !== -1) {
        this.notifications[index] = updatedNotification;
      }
    },

    // 加载消息类型
    async loadMessageTypes() {
      try {
        const response = await notificationsApi.getNotificationTypes();
        
        if (response.code === 200 && response.data) {
          this.setMessageTypes(response.data);
        } else {
          // 设置默认消息类型
          this.setMessageTypes({
            resume_review: '简历审核',
            application_recommend: '申请推荐',
            enterprise_contact: '企业联系',
            password_change: '密码修改',
            system_notification: '系统通知'
          });
        }
      } catch (error) {
        console.warn('加载消息类型失败，可能是通知服务未启动:', error.message);
        
        // 如果是404错误，说明通知服务不存在，设置默认值
        if (error.response && error.response.status === 404) {
          console.log('通知服务不存在，使用默认消息类型');
        }
        
        // 设置默认消息类型
        this.setMessageTypes({
          resume_review: '简历审核',
          application_recommend: '申请推荐',
          enterprise_contact: '企业联系',
          password_change: '密码修改',
          system_notification: '系统通知'
        });
      }
    },

    // 加载消息列表（支持分页）
    async loadNotifications(params = {}) {
      this.setLoading(true);
      try {
        // 根据用户类型选择API
        let response;
        const userType = params.recipient_type || 'student';
        
        if (userType === 'enterprise') {
          response = await notificationsApi.getEnterpriseNotificationsList(params);
        } else {
          response = await notificationsApi.getNotificationsList(params);
        }
        
        if (response.code === 200 && response.data) {
          // 更新分页信息
          if (response.totalMessages !== undefined) {
            this.setPagination({
              totalMessages: response.totalMessages,
              unreadCount: response.unreadCount,
              currentPage: response.currentPage || 1,
              pageSize: response.pageSize || 10,
              totalPages: response.totalPages || 1
            });
          }
          
          // 设置消息列表
          this.setNotifications(response.data);
          
          // 更新未读数量
          if (response.unreadCount !== undefined) {
            this.setUnreadCount(response.unreadCount);
          }
          
          return response.data;
        } else {
          throw new Error('Invalid response format');
        }
      } catch (error) {
        console.warn('加载消息失败，可能是通知服务未启动:', error.message);
        
        // 如果是404错误，说明通知服务不存在，设置空列表
        if (error.response && error.response.status === 404) {
          console.log('通知服务不存在，设置空消息列表');
        }
        
        this.setNotifications([]);
        return [];
      } finally {
        this.setLoading(false);
      }
    },

    // 刷新消息列表
    async refreshNotifications() {
      try {
        const response = await notificationsApi.refreshNotifications();
        
        if (response.code === 200 && response.data) {
          // 更新消息列表
          this.setNotifications(response.data);
          
          // 更新分页和统计信息
          if (response.totalMessages !== undefined) {
            this.setPagination({
              totalMessages: response.totalMessages,
              unreadCount: response.unreadCount
            });
          }
          
          // 更新未读数量
          if (response.unreadCount !== undefined) {
            this.setUnreadCount(response.unreadCount);
          }
          
          // 更新刷新时间
          if (response.refreshTime) {
            this.setLastRefreshTime(response.refreshTime);
          }
          
          return response.data;
        } else {
          throw new Error('Invalid response format');
        }
      } catch (error) {
        console.warn('刷新消息失败，可能是通知服务未启动:', error.message);
        
        // 如果是404错误，说明通知服务不存在，返回空列表
        if (error.response && error.response.status === 404) {
          console.log('通知服务不存在，跳过消息刷新');
        }
        
        return [];
      }
    },
    
    // 加载未读消息数量
    async loadUnreadCount() {
      try {
        const response = await notificationsApi.getUnreadCount();
        
        if (response.code === 200 && response.data !== undefined) {
          this.setUnreadCount(response.data);
          return response.data;
        } else {
          // 使用本地计算
          const count = this.notifications.filter(n => !n.isRead).length;
          this.setUnreadCount(count);
          return count;
        }
      } catch (error) {
        console.warn('加载未读消息数量失败，可能是通知服务未启动:', error.message);
        
        // 如果是404错误，说明通知服务不存在，使用本地计算
        if (error.response && error.response.status === 404) {
          console.log('通知服务不存在，使用本地计算的未读数量');
        }
        
        const count = this.notifications.filter(n => !n.isRead).length;
        this.setUnreadCount(count);
        return count;
      }
    },
    
    // 加载统计信息
    async loadStatistics() {
      try {
        const response = await notificationsApi.getNotificationsStatistics();
        
        if (response.code === 200 && response.data) {
          this.setStatistics(response.data);
          return response.data;
        } else {
          throw new Error('Invalid response format');
        }
      } catch (error) {
        console.warn('加载统计信息失败，可能是通知服务未启动:', error.message);
        
        // 如果是404错误，说明通知服务不存在，使用本地计算
        if (error.response && error.response.status === 404) {
          console.log('通知服务不存在，使用本地计算的统计信息');
        }
        
        // 使用本地计算
        const stats = {
          totalMessages: this.notifications.length,
          unreadCount: this.notifications.filter(n => !n.isRead).length,
          readCount: this.notifications.filter(n => n.isRead).length
        };
        this.setStatistics(stats);
        return stats;
      }
    },

    // 初始化消息中心
    async initializeNotifications(params = {}) {
      await Promise.all([
        this.loadMessageTypes(),
        this.loadNotifications(params),
        this.loadUnreadCount(),
        this.loadStatistics()
      ]);
    },

    // 获取消息详情
    async getNotificationDetail(notificationId) {
      try {
        const response = await notificationsApi.getNotificationDetail(notificationId);
        
        // 按照接口规范处理响应
        if (response.code === 200 && response.data) {
          return response.data;
        } else {
          console.error('获取消息详情失败:', response.message || '未知错误');
          return null;
        }
      } catch (error) {
        console.warn('获取消息详情失败，可能是通知服务未启动:', error.message);
        
        // 如果是404错误，说明通知服务不存在，返回null
        if (error.response && error.response.status === 404) {
          console.log('通知服务不存在，无法获取消息详情');
        }
        
        return null;
      }
    }
  }
}); 